<template>
  <div class="content">
    <div class="search">
      <el-form
        :inline="true"
        :model="goodsParams"
        class="demo-form-inline"
      >
        <el-form-item label="商品名称">
          <el-input v-model="goodsParams.goodsName" autocomplete="off" placeholder="请输入商品名称" clearable />
        </el-form-item>
        <el-form-item label="商铺:">
          <el-select style="width: 160px;" clearable v-model="goodsParams.storeCode" placeholder="请选择" @change="searchStoreChange">
            <el-option v-for="(item,index) in storeList" :key="index" :label="item.name" :value="item.code" />
          </el-select>
        </el-form-item>
        <el-form-item label="分类:">
          <el-select style="width: 160px;" clearable v-model="goodsParams.categoryCode" placeholder="请选择">
            <el-option v-for="(item,index) in categoryListSearch" :key="index" :label="item.name" :value="item.code" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态:">
          <el-select style="width: 160px;" clearable v-model="goodsParams.status" placeholder="请选择">
            <el-option label="上架" :value="1" />
            <el-option label="下架" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getSearch">查询</el-button>
          <el-button type="primary" @click="addFn">新增</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table">
      <el-table
        :data="goodsList"
        :header-cell-style="{ color: '#000', background: '#EEF5FE' }"
        height="100%"
        border
        empty-text="暂无数据"
        stripe
      >
        <el-table-column label="ID" align="center" prop="id" />
        <el-table-column label="商品名称" align="center" prop="name" />
        <el-table-column label="价格" align="center" prop="price" />
        <el-table-column label="图片" align="center">
          <template #default="{ row }">
            <view class="imgs">
              <el-image
                v-for="(item, index) in row.imgList"
                :key="index"
                style="width: 50px; height: 50px; margin-right: 10px"
                :src="item"
                :preview-teleported="true"
                :max-scale="7"
                :min-scale="1"
                :preview-src-list="row.imgList"
                :initial-index="index"
                fit="cover"
              />
            </view>
          </template>
        </el-table-column>
        <el-table-column label="描述" align="center" prop="describe" />
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="创建时间" align="center" prop="createTime" />
        <el-table-column label="创建时间" align="center" prop="createTime" />
        <el-table-column label="状态" align="center">
          <template #default="{ row }">
            <el-tag v-if="row.status == 1" type="success">上架</el-tag>
            <el-tag v-else type="danger">下架</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="{ row }">
            <el-button type="primary" @click="editFn(row)">编辑</el-button>
            <el-button v-if="row.status == 2" type="success" @click="shelves(row)">上架</el-button>
            <el-button v-if="row.status == 1" type="danger" @click="shelves(row)">下架</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog :close-on-click-modal="false" v-model="dialogFormVisible" :title="dialogType=='add'?'新增':'编辑'">
      <el-form ref="ruleFormRef" :model="goodsForm" :rules="rules">
        <el-form-item prop="name" label="商品名称" :label-width="formLabelWidth">
          <el-input v-model="goodsForm.name" autocomplete="off" placeholder=" 请输入商品名称" />
        </el-form-item>
        <el-form-item prop="price" label="价格" :label-width="formLabelWidth">
          <el-input type="number" v-model="goodsForm.price" autocomplete="off" placeholder="请输入价格" />
        </el-form-item>
        <el-form-item prop="storeCode" label="商铺" :label-width="formLabelWidth">
          <el-select v-model="goodsForm.storeCode" placeholder="请选择商铺" @change="formStoreChange">
            <el-option v-for="(item,index) in storeList" :key="index" :label="item.name" :value="item.code" />
          </el-select>
        </el-form-item>
        <el-form-item prop="categoryCode" label="分类" :label-width="formLabelWidth">
          <el-select v-model="goodsForm.categoryCode" placeholder="请选择分类">
            <el-option v-for="(item,index) in categoryList" :key="index" :label="item.name" :value="item.code" />
          </el-select>
        </el-form-item>
        <el-form-item prop="status" label="是否上架" :label-width="formLabelWidth">
          <el-select v-model="goodsForm.status" placeholder="请选择是否上架">
            <el-option label="上架" value="1" />
            <el-option label="下架" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item prop="describe" label="描述" :label-width="formLabelWidth">
          <el-input v-model="goodsForm.describe" autocomplete="off" placeholder="请输入描述" />
        </el-form-item>
        <el-form-item prop="remark" label="备注" :label-width="formLabelWidth">
          <el-input v-model="goodsForm.remark" autocomplete="off" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item prop="stock" label="库存" :label-width="formLabelWidth">
          <el-input type="number" v-model="goodsForm.stock" autocomplete="off" placeholder="请输入亏存，-1为不限量" />
        </el-form-item>
        <el-form-item prop="rank" label="排序" :label-width="formLabelWidth">
          <el-input type="number" v-model="goodsForm.rank" autocomplete="off" placeholder="请输入排序" />
        </el-form-item>
        <el-form-item label="图片" required :label-width="formLabelWidth">
          <el-upload
            class="upload-demo"
            action="https://xyx.xintujing.online:8000/api/upload"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            multiple
            list-type="picture-card"
            :limit="3"
            :on-exceed="handleExceed"
            :on-success="handleSuccess"
            :file-list="fileList"
            :headers="{
              Authorization: 'Bearer ' + token
            }"
          >
            <el-icon><Plus /></el-icon>
            <template #tip>
              <div class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </template>
          </el-upload>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">关闭</el-button>
          <el-button type="primary" @click="submitForm(ruleFormRef)">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { getGoodsList,addGoods,editGoods,getCategoryList } from '@/api/home.js'
import { ElMessage,ElMessageBox } from 'element-plus'
import { onMounted, reactive, ref, computed } from "vue";
const props = defineProps({
  dataList: {
    type: Array,
    default: [],
  },
  storeList: {
    type: Array,
    default: [],
  },
  categoryList: {
    type: Array,
    default: [],
  }
});
const token = computed(() => {
  return JSON.parse(localStorage.getItem('yxUserInfo')).token || ""
})
const goodsParams = ref({});
const ruleFormRef = ref();
const fileList = ref([]);
const dialogFormVisible = ref(false);
const dialogType = ref('add');
const formLabelWidth = '120px';
const goodsForm = reactive({});
const rules = reactive({
  name: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
  ],
  price: [
    { required: true, message: '请输入价格', trigger: 'blur' },
  ],
  status: [
    { required: true, message: '请选择是否上架', trigger: 'blur' }
  ],
  storeCode: [
    { required: true, message: '请选择商铺', trigger: 'blur' }
  ],
  categoryCode: [
    { required: true, message: '请选择分类', trigger: 'blur' }
  ],
  stock:[
    { required: true, message: '请输入库存', trigger: 'blur' }
  ]
});
const getCategoryData = async (storeCode,type)=>{
  const res = await getCategoryList({storeCode})
  if (res.code==0) {
    if (type=='search') {
      categoryListSearch.value.length = 0
      categoryListSearch.value.push(...res.data.list)
    }else if (type=='form') {
      categoryListForm.value.length = 0
      categoryListForm.value.push(...res.data.list)
    }
  }
};
const searchStoreChange = (val) => {
  getCategoryData(val,"search")
  goodsParams.value.categoryCode = ''
};
const formStoreChange = (val) => {
  getCategoryData(val,"form")
  goodsForm.categoryCode = ''
};

const handleRemove = (file, files) => {
  fileList.value = []
  fileList.value.push(...files)
};
const handleExceed = (files, fileList) => {
  ElMessage.error(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
    files.length + fileList.length
  } 个文件`)
};
const beforeRemove = (file, fileList) => {
  return ElMessageBox.confirm(`确定移除 ${file.name}？`).then(() => true).catch(() => false)
};
const handleSuccess = (file,files) => { 
  fileList.value.push(files)
}
const goodsList = computed(() => {
  return props.dataList;
});
const categoryListSearch = computed(() => {
  return props.categoryList;
});
const categoryListForm = computed(() => {
  return props.categoryList;
});

const getSearch = async () => {
  goodsList.value.length = 0
  const res = await getGoodsList(goodsParams.value)
  if (res.code==0) {
    res.data.list.forEach(item=>{
      if (item.imgUrl) {
        item.imgList = item.imgUrl.split(',')
      }else{
        item.imgList = []
      }
    })
    goodsList.value.push(...res.data.list)
  }
};
const submitForm = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (fileList.value.length==0) {
        ElMessage.error('请上传图片')
        return
      }
      goodsForm.imgUrl = fileList.value.map(item=>item.response.data).join(',')
      console.log(231,goodsForm);
      if (dialogType.value == 'add') {
        addGoods(goodsForm).then(res=>{
          if (res.code==0) {
            ElMessage.success('添加成功')
            dialogFormVisible.value = false
            getSearch()
          }
        })
      } else {
        editGoods(goodsForm).then(res=>{
          if (res.code==0) {
            ElMessage.success('修改成功')
            dialogFormVisible.value = false
            getSearch()
          }
        })
      }
      
    } else {
      console.log('error submit!', fields);
    }
  });
};
// addFn
const addFn = () => {
  fileList.value = [];
  dialogFormVisible.value = true;
  ruleFormRef.value.resetFields();
  dialogType.value = 'add';
  goodsForm.name = ""
  goodsForm.price = ""
  goodsForm.status = "1"
  goodsForm.rank = 0
  goodsForm.storeCode = ""
  goodsForm.categoryCode = ""
  goodsForm.imgUrl = ""
  goodsForm.remark = ""
  goodsForm.describe = ""
};
// editFn
const editFn = (row) => {
  console.log('editFn',row);
  dialogFormVisible.value = true;
  dialogType.value = 'edit';
  Object.assign(goodsForm,row)
  fileList.value = row.imgList.map(item=>{
    return {
      name: item,
      url: item,
      response: {
        data: item
      }
    }
  })
};
// 上架、下架
const shelves = async (row) => {
  ElMessageBox.confirm(
    `确定${row.status == '1' ? '下架' : '上架'}该商品吗?`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(async () => {
    row.status = row.status == '1' ? '2' : '1'
    Object.assign(goodsForm,row)
    fileList.value = row.imgList.map(item=>{
      return {
        name: item,
        url: item,
        response: {
          data: item
        }
      }
    })
    editGoods(goodsForm).then(res=>{
      if (res.code==0) {
        ElMessage.success('修改成功')
        // getSearch()
      }
    })
  })
};

onMounted(() => {
  console.log(props);
});

const previewImage = (url) => {};
</script>

<style lang="less" scoped>
.content{
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}
.imgs {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  img {
    margin-right: 10px;
  }
}
.table{
  flex: 1;
  overflow-y: auto;
}
</style>